<!-- src/components/Login.vue -->
<template>
    <div class="auth-container">
        <div class="auth-card">
            <h2>用户登录</h2>
            <form @submit.prevent="handleLogin">
                <div class="form-group">
                    <label>用户名：</label>
                    <input 
                        v-model="form.username" 
                        type="text" 
                        required
                        class="form-control"
                    >
                </div>
                <div class="form-group">
                    <label>密码：</label>
                    <input 
                        v-model="form.password" 
                        type="password" 
                        required
                        class="form-control"
                    >
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn btn-primary">登录</button>
                    <button type="button" @click="$router.push('/register')" class="btn btn-secondary">
                        去注册
                    </button>
                    <button type="button" @click="$router.push('/')" class="btn btn-secondary">
                        取消
                    </button>
                </div>
            </form>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import store from '../store/index.js'

const router = useRouter()
const form = ref({
    username: '',
    password: ''
})
const handleLogin = () => {
    // 确保从localStorage获取的是数组
    let users = JSON.parse(localStorage.getItem('users') || '[]')
    
    // 确保users是数组类型
    if (!Array.isArray(users)) {
        users = []
    }
    
    const user = users.find(u => 
        u.username === form.value.username && 
        u.password === form.value.password
    )
    
    if (user) {
        store.setUser(user)
        localStorage.setItem('user', JSON.stringify(user))
        router.push('/todo')
    } else {
        alert('用户名或密码错误！')
    }
}
</script>
<style scoped>
.alert-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.alert-popup {
    background-color: white;
    padding: 20px 30px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    text-align: center;
    font-size: 16px;
    font-weight: 500;
}
</style>